﻿using B.S.BaseData.Api.Write.Applicantion.Command.RBAC;
using B.S.BaseData.Api.Write.GetCelim;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.RBAC;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.RBAC
{
    public class RoleUpdateCommandHandler : IRequestHandler<RoleUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _rolerepository;
        private readonly IBaseRepository<RolePermissionsModel> _rolepermissionrepository;
        private readonly IIdContextCemil _idContextCemil;
        public RoleUpdateCommandHandler(IBaseRepository<RoleModel> rolerepository, IBaseRepository<RolePermissionsModel> rolepermissionrepository, IIdContextCemil idContextCemil)
        {
            _rolerepository = rolerepository;
            _rolepermissionrepository = rolepermissionrepository;
            _idContextCemil = idContextCemil;
        }
        public async Task<APIResult<int>> Handle(RoleUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            var list =await _rolerepository.GetValues(x=>x.Id==request.Id);
            list.RoleName = request.RoleName;
            await _rolerepository.UpdateAsync(list);

            var res = _rolepermissionrepository.GetAll().Where(x => x.RoleId == request.Id).ToList();
            foreach (var id in res)
            {
                await _rolepermissionrepository.Delete(id);
            }

            foreach (var item in request.Qxsz1)
            {
                RolePermissionsModel rolepermissions = new RolePermissionsModel();
                rolepermissions.Id=YitIdHelper.NextId();
                rolepermissions.RoleId=request.Id;
                rolepermissions.PermissionsId =item;
                rolepermissions.CreateName = _idContextCemil.UserName;
                await _rolepermissionrepository.CreateAsync(rolepermissions);
            }
            result.Code = ApiEnum.Success;
            result.Msg = "角色信息修改成功";
            result.Data = 1;
            return await Task.FromResult(result);
        }
    }
}
